﻿using Architecture.CrossCutting.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.CrossCutting.Web.WCF
{

    public class WcfCustomContextStorage : IExtension<InstanceContext>
    {
        private readonly IDictionary items = new Hashtable();

        public IDictionary Items
        {
            get { return items; }
        }

        internal static WcfCustomContextStorage Current
        {
            get
            {
                WcfCustomContextStorage context = OperationContext.Current.InstanceContext.Extensions.Find<WcfCustomContextStorage>();
                if (context == null)
                {
                    context = new WcfCustomContextStorage();
                    OperationContext.Current.InstanceContext.Extensions.Add(context);
                }
                return context;
            }
        }
        public void Attach(InstanceContext owner) { }

        public void Detach(InstanceContext owner) { }
    }

    public class WcfCustomContext : IExecutionContext
    {

        public Guid ExecutionId
        {
            get
            {
                if (WcfCustomContextStorage.Current.Items["ExecutionId"] == null)
                {
                    WcfCustomContextStorage.Current.Items["ExecutionId"] = Guid.NewGuid();
                }
                return (Guid)WcfCustomContextStorage.Current.Items["ExecutionId"];
            }
            set
            {
                WcfCustomContextStorage.Current.Items["ExecutionId"] = value;
            }
        }

    }
}
